/* eslint-disable eqeqeq */
// app/service/user.js
const fs = require('fs');
const path = require('path');
const Service = require('egg').Service;

class FileService extends Service {
  async addfile() {
    const { ctx } = this;
    const file = ctx.request.files[0];
    const fileName = file?.filename;
    const fileinfo = fs.readFileSync(file.filepath);
    const fileSize = fs.statSync(file.filepath).size;
    const arr = file.filename.split('.');
    const filename = new Date().getTime() + '.' + arr[arr.length - 1];
    const target = path.join('app/public/uploads', filename);

    try {
      await fs.writeFileSync(target, fileinfo);
    } catch (error) {
      throw error;
    } finally {
      await fs.promises.unlink(file.filepath, err => {
        if (err) {
          throw err;
        }
      });
    }
    return {
      name: fileName,
      size: fileSize,
      path: 'http://' + ctx.host + `/public/uploads/${filename}`,
    };
  }
}

module.exports = FileService;
